<template>
  <div class="header-select">
    <!--组织结构-->
    <div class="header-select-head">
      <div class="select-project" @click="showDialog">
        <div style="display: flex">
          <i class="el-icon-loading location-icon" v-if="projectLoading" />
          <svg-icon icon-class="location" class="location-icon" v-else />
          <el-popover
            placement="bottom-start"
            width="400"
            :disabled="selectProjectName.length < 15"
            trigger="hover"
          >
            <el-alert
              :title="selectProjectName"
              :closable="false"
              type="info"
            />
            <span slot="reference" class="project-name">{{ selectProjectName }}</span>
          </el-popover>
        </div>
        <i class="el-icon-arrow-down" style="color: #c4dbe6" />
      </div>
      <el-select v-if="level > 1" v-model="buildingId" size="small" class="select-building" placeholder="请选择" @change="selectChange">
        <el-option
          v-for="item in buildings"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-select
        v-if="level > 2"
        v-model="checkTableId"
        size="small"
        class="select-checktable"
        filterable
        placeholder="请选择"
        @change="selectCheckTable"
      >
        <el-option
          v-for="item in processList"
          :key="item.fid"
          :label="item.fnameL2"
          :value="item.fid"
        />
      </el-select>
    </div>

    <el-dialog
      title="选择项目"
      width="500px"
      :visible.sync="dialogVisible"
      append-to-body
      :close-on-click-modal="false"
    >
      <div class="aside-tree-container">
        <div>
          <el-input
            v-model="deptName"
            placeholder="请输入项目名称 → 回车检索"
            clearable
            size="mini"
            prefix-icon="el-icon-search"
            style="margin-bottom: 12px;width: 240px;margin-left: 20px;margin-right: 10px"
            @keyup.enter.native="searchProject"
          />
          <el-button type="primary" size="mini" icon="el-icon-search" @click="searchProject">搜索</el-button>
        </div>
        <el-scrollbar style="height: calc(70vh - 90px);font-size: 12px;">
          <el-tree
            ref="tree"
            node-key="fid"
            :data="deptOptions"
            :props="defaultProps"
            accordion
            highlight-current
            :expand-on-click-node="false"
            :filter-node-method="filterNodeDept"
            :default-expanded-keys="expandKeys"
            @node-click="handleNodeClickDept"
          >
            <div slot-scope="{ node, data }">
              <svg-icon v-if="data.type === 'dept'" icon-class="ico_area" class="preview-icon" />
              <svg-icon
                v-else-if="data.type === 'project'"
                class="preview-icon"
                style="color: #416ca6;"
                icon-class="druid"
              />
              <svg-icon
                v-else-if="data.type === 'building'"
                class="preview-icon"
                icon-class="ico_city"
                @click.stop="plateProjectDevices(data)"
              />
              <span style="padding-left: 6px;">{{ node.label }}</span>
            </div>
          </el-tree>
        </el-scrollbar>
      </div>
      <div class="select-project-btn">
        <el-button type="primary" @click="treeType === 'project' ? submitProject(true) : submitDept()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// TODO 复制自 @/views/statement/components/HeaderSelect，待优化
import { buildingList } from '@/api/common'
import { listCheckTable } from '@/api/qualityManage/checkTable'
import { authtreeselect } from '@/api/system/dept'
import { getAuthCurProject } from '@/api/cq/routeInspection'

export default {
  name: 'HeaderSelect',
  props: {
    level: { // 展示、返回数据层次 1: 项目，2: 楼栋， 3：工序
      type: Number,
      default: () => 1
    },
    type: { // 0: 项目前期名 1：项目后期名称
      type: Number,
      default: () => 1
    },
    treeType: { // project: 显示到项目 dept：部门
      type: String,
      default: () => 'project'
    },
    isStatement: { // 是否 进度报表模块 路由跳转
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      value: '',
      deptName: '',
      projectLoading: false,
      deptOptions: [],
      buildings: [],
      defaultProps: {
        children: 'children',
        // label: 'name'
        label: function(data, node) {
          if (data.cflastname !== undefined) {
            return data.cflastname
          } else if (data.label !== undefined) {
            return data.label
          }
        }
      },
      expandKeys: [], // 组织项目
      selectProject: {}, // 选择的项目对象
      selectProjectName: '',
      dialogVisible: false,
      nodeKey: 'id',
      currentProject: null,
      buildingId: '',
      checkTableId: '',
      processList: [],
      changeProjectStatus: false,
      currentDept: null,
      selectDept: {}
    }
  },
  watch: {
    '$route.query'(val) {
      if (val.buildingId !== undefined && val.buildingId !== this.buildingId) {
        this.buildingId = this.$route.query.buildingId
      }
      if (val.checkTableId !== undefined && val.checkTableId !== this.checkTableId) {
        this.checkTableId = this.$route.query.checkTableId
      }
    }
  },
  created() { // 初始化
    this.currentProject = JSON.parse(localStorage.getItem('currentProject'))
    this.currentDept = JSON.parse(localStorage.getItem('currentDept'))
    this.getTreeselect()
    // if (this.level === 'building') {
    //   this.nodeKey = 'id'
    // } else if (this.level === 'unit') {
    //   this.nodeKey = 'fid'
    // }
    // this.$eventBus.$on('unitUpdate', () => {
    //   this.getBuildingsByPro(this.selectProject.id)
    // })
  },
  activated() { // 缓存页面显示 初始化
    this.currentProject = JSON.parse(localStorage.getItem('currentProject'))
    if (this.currentProject.id !== this.selectProject.id) {
      this.getTreeselect()
    }
    if (this.buildingId && this.buildingId !== this.$route.query.buildingId) {
      this.getBuildingsByPro(this.selectProject.id)
    }
  },
  beforeDestroy() {
    // 关闭监听事件
    this.$eventBus.$off('unitUpdate')
  },
  methods: {
    // 检索
    searchProject() {
      this.$refs.tree.filter(this.deptName)
    },
    getTreeselect() {
      if (this.treeType === 'project') {
        this.getProjectTree()
      } else {
        this.getDeptTree()
      }
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      this.projectLoading = true
      authtreeselect().then((response) => {
        this.projectLoading = false
        this.deptOptions = response.data
        const datas = [...response.data]
        this.expandKeys = [response.data[0].id]
        if (this.currentDept) {
          this.selectDept = { ...this.currentDept }
          this.submitDept()
          return
        }
        if (datas.length > 0) {
          this.selectProjectName = datas[0].label
          this.selectDept = { ...datas[0] }
          this.submitDept()
        }
      }).finally(() => {
        this.projectLoading = false
      })
      // const self = this
      // function recursion(datas) { // 递归获取第一个部门ID
      //   if (datas[0].type === 'project') {
      //     console.log(datas[0])
      //     self.selectProjectName = datas[0].label
      //     self.selectDept = { ...datas[0] }
      //     self.submitDept()
      //   } else if (datas[0].children && datas[0].children.length > 0) {
      //     recursion(datas[0].children)
      //   }
      // }
    },
    /** 查询部门与项目下拉树结构 */
    getProjectTree() {
      this.projectLoading = true
      const opt = { isResponsible: 0 }
      getAuthCurProject(opt).then((response) => {
        this.projectLoading = false
        this.deptOptions = response.data
        const datas = [...response.data]
        this.expandKeys = [response.data[0].fid]
        if (this.currentProject && datas.some(project => project.fid === this.currentProject.id)) {
          this.selectProject = { ...this.currentProject }
          this.submitProject()
          return
        }
        if (datas.length > 0) {
          // recursion(datas[0].children)
          this.selectProjectName = datas[0].cflastname
          const project = { ...datas[0] }
          this.selectProject = {
            id: project.fid,
            lastname: project.cflastname,
            leaf: true,
            name: project.cflastname,
            parentId: project.fparentid,
            type: 'project'
          }
          this.submitProject()
        } else {
          this.$emit('selectProject', null)
        }
      }).catch(() => {
        this.$emit('selectProject', null)
      }).finally(() => {
        this.projectLoading = false
      })
      // const self = this
      // function recursion(datas) { // 递归获取第一个项目ID
      //   if (datas[0].type === 'project') {
      //     self.selectProjectName = datas[0].name
      //     self.selectProject = { ...datas[0] }
      //     self.submitProject()
      //   } else if (datas[0].children && datas[0].children.length > 0) {
      //     recursion(datas[0].children)
      //   }
      // }
    },
    /** 根据项目ID获取楼栋 */
    getBuildingsByPro(projectId) {
      this.projectLoading = true
      buildingList({ projectId }).then((response) => {
        this.buildings = response.data
        this.projectLoading = false
        if (response.data.length > 0) {
          if (this.changeProjectStatus) {
            this.changeProjectStatus = false
            this.replaceBuildingId(response.data[0].id)
            this.buildingId = response.data[0].id
          } else {
            this.buildingId = this.$route.query.buildingId
            for (let i = 0; i < this.buildings.length; i++) {
              if (this.buildings[i].id === this.buildingId) {
                this.$emit('selectBuildingObject', { ...this.buildings[i] })
              }
            }
          }
          if (this.level > 2) {
            this.getListCheckTable()
          }
        }
      }).finally(() => {
        this.projectLoading = false
      })
    },
    /** 获取验收工序项 */
    getListCheckTable() {
      listCheckTable().then(
        (response) => {
          this.processList = response.data
          this.checkTableId = this.$route.query.checkTableId
        }
      ).catch(() => {
      })
    },

    // 组织筛选节点
    filterNodeDept(value, data, node) {
      if (!value) return true
      // return data.label.indexOf(value) !== -1
      let parentNode = node.parent
      let labels = [node.label]
      let level = 1
      while (level < node.level) {
        labels = [...labels, parentNode.label]
        parentNode = parentNode.parent
        level++
      }
      return labels.some(label => label && label.indexOf(value) !== -1)
    },
    // 组织的项目节点节点单击事件
    handleNodeClickDept(data, node) {
      console.log(data)
      this.changeProjectStatus = true
      if (this.treeType === 'project') {
        this.selectProject = {
          id: data.fid,
          lastname: data.cflastname,
          leaf: true,
          name: data.cflastname,
          parentId: data.fparentid,
          type: 'project'
        }
      } else {
        this.selectDept = data
      }
    },
    showDialog() {
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(this.selectProject.id)
      })
    },
    submitProject(isClick = false) {
      // console.log(this.selectProject)
      // if (process.env.NODE_ENV === 'development') { // 测试使用
      //   // this.selectProject.id = '14BhQdVOSwyOLB45K3wGb/nl6Ss='
      //   this.selectProject.id = 'x9oAABQjG2X55ekr'
      //   this.selectProject.name = '项目160'
      // }
      localStorage.setItem('currentProject', JSON.stringify(this.selectProject))
      this.dialogVisible = false
      this.selectProjectName = this.selectProject.name
      if (this.level > 1) {
        this.getBuildingsByPro(this.selectProject.id)
      }
      this.$emit('selectProject', { ...this.selectProject })
      if (isClick && this.isStatement) { // 手动切换项目 且在报表管理模块中
        if (this.$route.path !== '/statement/ProcessConstruct') {
          this.$router.replace({ path: '/statement/ProcessConstruct' })
        }
        const batch = {
          path: '/statement/Batch',
          name: 'Batch'
        }
        const roleCheck = {
          path: '/statement/RoleCheck',
          name: 'RoleCheck'
        }
        this.$store.commit('tagsView/DEL_VISITED_VIEW', batch)
        this.$store.commit('tagsView/DEL_CACHED_VIEW', batch)
        this.$store.commit('tagsView/DEL_VISITED_VIEW', roleCheck)
        this.$store.commit('tagsView/DEL_CACHED_VIEW', roleCheck)
      }
    },
    // 选择部门
    submitDept() {
      localStorage.setItem('currentDept', JSON.stringify(this.selectDept))
      this.dialogVisible = false
      this.selectProjectName = this.selectDept.label
      this.$emit('selectDept', { ...this.selectDept })
    },
    // 项目筛选节点
    filterNodePro(value, data, node) {
      if (!value) return true
      // return data.name.indexOf(value) !== -1
      let parentNode = node.parent
      let labels = [node.label]
      let level = 1
      while (level < node.level) {
        labels = [...labels, parentNode.label]
        parentNode = parentNode.parent
        level++
      }
      return labels.some(label => label.indexOf(value) !== -1)
    },
    // 选择楼栋
    selectChange(buildingId) {
      // this.$router.replace({ path: '/statement/Batch', query: { buildingId: buildingId }})
      this.replaceBuildingId(buildingId)
      if (this.isStatement) {
        if (this.$route.path !== '/statement/Batch') {
          this.$router.replace({ path: '/statement/Batch', query: { buildingId: buildingId }})
        }
        const roleCheck = {
          path: '/statement/RoleCheck',
          name: 'RoleCheck'
        }
        this.$store.commit('tagsView/DEL_VISITED_VIEW', roleCheck)
        this.$store.commit('tagsView/DEL_CACHED_VIEW', roleCheck)
      }
    },
    // 替换URL楼栋id
    replaceBuildingId(buildingId) {
      console.log(buildingId)
      const path = this.$route.path
      // const query = this.$route.query
      const query = { ...this.$route.query }
      console.log(query)
      if (query.buildingId !== buildingId) {
        this.$emit('selectBuilding', buildingId)
        for (let i = 0; i < this.buildings.length; i++) {
          if (this.buildings[i].id === this.buildingId) {
            this.$emit('selectBuildingObject', { ...this.buildings[i] })
          }
        }
        query.buildingId = buildingId
        this.$router.replace({ path: path, query: query })
      }
    },
    // 选择验收工序
    selectCheckTable(checkTableId) {
      this.$emit('selectCheckTable', { checkTableId })
    }
  }
}
</script>

<style scoped lang='scss'>
  .header-select {
    display: inline-block;
    font-size: 12px;
    .header-select-head {
      display: flex;
      align-items: center;
      .select-project {
        box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.2);
        height: 28px;
        display: flex;
        font-size: 14px;
        padding: 0 10px;
        justify-content: space-between;
        align-items: center;
        background-color: #ecf5ff;
        color: #606266;
        cursor: pointer;
        .location-icon {
          font-size: 16px;
          color: #409EFF;
        }
        .project-name {
          margin: 0 10px 0 6px;
          display: inline-block;
          min-width: 100px;
          max-width: 200px;
          overflow-x: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .select-building {
        margin-left: 20px;
        width: 160px;
      }
      .select-checktable {
        margin-left: 20px;
        width: 200px;
      }
    }
    .project-content {
      padding-left: 10px;
      .project-search {
        padding-right: 10px;
      }
    }
    .preview-icon {}
    .tree-label {
      padding-left: 6px;
    }
  }
  .select-project-btn {
    padding: 20px 30px 0 0;
    display: flex;
    justify-content: flex-end;
  }
</style>
<style lang="scss">
  .check-type-scrollbar-container,
  .aside-tree-container {
    .el-scrollbar .el-scrollbar__wrap {
      overflow-x: hidden;
    }
  }
</style>
